import { getRequest } from './api';

export const initMenu = (router, store) => {

  //判断当前是否已存在菜单项
  if (store.state.routes.length > 0) {
    return
  }

  getRequest('/system/config/menu').then(data => {
    if (data) {
      //初始化后端传过来的JSON菜单数据
      let fmtRoutes = formatRoutes(data)
      router.addRoutes(fmtRoutes)
      store.commit('initRoutes',fmtRoutes)
    }
  })
}

export const formatRoutes = (routes) => {
  let fmRoutes = []

  routes.forEach(router => {
    let {
      path,
      component,
      name,
      meta,
      iconCls,
      children
    } = router

    if (children && children instanceof Array) {
      //如果有子菜单递归调用
      children = formatRoutes(children)
    }

    let fmRouter = {
      path: path,
      name: name,
      iconCls: iconCls,
      meta: meta,
      children: children,
      component(resolve) {
        require(['../views/' + component + '.vue'], resolve)
      }
    };
    fmRoutes.push(fmRouter)
  });

  return fmRoutes
}